/*
 * XXX
 */

package edu.uhcl.csci4838.group3.view;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.Toast;
import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourse;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTask;
import edu.uhcl.csci4838.group3.database.info.Course;
import edu.uhcl.csci4838.group3.database.info.CourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.info.Task;
import edu.uhcl.csci4838.group3.view.help.HelpActivity;

/**
 * XXX
 * 
 * @author Chris Waguespack
 */
public class TaskListActivity extends ExpandableListActivity {
	
	/**
	 * XXX
	 * 
	 * @author Chris Waguespack
	 */
	private static class TaskListCursorTreeAdapter extends
			SimpleCursorTreeAdapter {
		/**
		 * XXX
		 * 
		 * @param context
		 *            XXX
		 * @param cursor
		 *            XXX
		 * @param collapsedGroupLayout
		 *            XXX
		 * @param expandedGroupLayout
		 *            XXX
		 * @param groupFrom
		 *            XXX
		 * @param groupTo
		 *            XXX
		 * @param childLayout
		 *            XXX
		 * @param lastChildLayout
		 *            XXX
		 * @param childFrom
		 *            XXX
		 * @param childTo
		 *            XXX
		 */
		public TaskListCursorTreeAdapter(final Context context,
				final Cursor cursor,
				final int collapsedGroupLayout,
				final int expandedGroupLayout,
				final String[] groupFrom,
				final int[] groupTo,
				final int childLayout,
				final int lastChildLayout,
				final String[] childFrom,
				final int[] childTo) {
			super(context,
					cursor,
					collapsedGroupLayout,
					expandedGroupLayout,
					groupFrom,
					groupTo,
					childLayout,
					lastChildLayout,
					childFrom,
					childTo);
		}
		
		/**
		 * XXX
		 * 
		 * @param context
		 *            XXX
		 * @param cursor
		 *            XXX
		 * @param collapsedGroupLayout
		 *            XXX
		 * @param expandedGroupLayout
		 *            XXX
		 * @param groupFrom
		 *            XXX
		 * @param groupTo
		 *            XXX
		 * @param childLayout
		 *            XXX
		 * @param childFrom
		 *            XXX
		 * @param childTo
		 *            XXX
		 */
		public TaskListCursorTreeAdapter(final Context context,
				final Cursor cursor,
				final int collapsedGroupLayout,
				final int expandedGroupLayout,
				final String[] groupFrom,
				final int[] groupTo,
				final int childLayout,
				final String[] childFrom,
				final int[] childTo) {
			super(context,
					cursor,
					collapsedGroupLayout,
					expandedGroupLayout,
					groupFrom,
					groupTo,
					childLayout,
					childFrom,
					childTo);
		}
		
		/**
		 * XXX
		 * 
		 * @param context
		 *            XXX
		 * @param cursor
		 *            XXX
		 * @param groupLayout
		 *            XXX
		 * @param groupFrom
		 *            XXX
		 * @param groupTo
		 *            XXX
		 * @param childLayout
		 *            XXX
		 * @param childFrom
		 *            XXX
		 * @param childTo
		 *            XXX
		 */
		public TaskListCursorTreeAdapter(final Context context,
				final Cursor cursor,
				final int groupLayout,
				final String[] groupFrom,
				final int[] groupTo,
				final int childLayout,
				final String[] childFrom,
				final int[] childTo) {
			super(context,
					cursor,
					groupLayout,
					groupFrom,
					groupTo,
					childLayout,
					childFrom,
					childTo);
		}
		
		/**
		 * XXX
		 * 
		 * @param groupCursor
		 *            XXX
		 * @return XXX
		 */
		/* 
		 * (non-Javadoc)
		 * 
		 * @see android.widget.CursorTreeAdapter#getChildrenCursor(android.database.Cursor)
		 */
		@Override
		@SuppressWarnings("synthetic-access")
		protected Cursor getChildrenCursor(final Cursor groupCursor) {
			if (!(groupCursor instanceof CursorCourseCategoryWeight)) {
				Log.e("BackpackEDU",
						"Group cursor is not a category cursor.");
				throw new ClassCastException("Group cursor is not a category cursor.");
			}
			
			final ContentValues criteria = new ContentValues();
			criteria.put(Task.COURSE_ID,
					Long.valueOf(((CursorCourseCategoryWeight) groupCursor).getColCourseId()));
			criteria.put(Task.CATEGORY_NAME,
					((CursorCourseCategoryWeight) groupCursor).getColCategoryName());
			return TaskListActivity.dbHelper.getTask(criteria,
					new String[] { Task.DATE_DUE },
					true);
		}
	}
	
	/**
	 * The database helper object.
	 */
	private static BackpackEduDatabaseHelper dbHelper;
	
	/**
	 * The adapter used to bind data to this list.
	 */
	private TaskListCursorTreeAdapter adapter;
	
	/**
	 * A list of the opened group positions;
	 */
	private ArrayList<Integer> openedGroups;
	
	/**
	 * The id of the course that these tasks belong to.
	 */
	private long courseId;
	
	/**
	 * XXX
	 * 
	 * @param parent
	 *            XXX
	 * @param v
	 *            XXX
	 * @param groupPosition
	 *            XXX
	 * @param childPosition
	 *            XXX
	 * @param id
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ExpandableListActivity#onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long)
	 */
	@Override
	public boolean onChildClick(final ExpandableListView parent,
			final View v,
			final int groupPosition,
			final int childPosition,
			final long id) {
		this.adapter.getCursor()
				.moveToPosition(groupPosition);
		
		// Get the task cursor
		final CursorTask taskCursor = (CursorTask) this.adapter.getChildrenCursor(this.adapter.getCursor());
		taskCursor.moveToPosition(childPosition);
		
		// Start task activity
		final Intent intent = new Intent(this.getApplicationContext(),
				TaskActivity.class);
		intent.putExtra(this.getString(R.string.intent_extra_taskId),
				taskCursor.getColId());
		taskCursor.close();
		this.startActivity(intent);
		return true;
	}
	
	/**
	 * XXX
	 * 
	 * @param item
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(final MenuItem item) {
		
		// Get information about the selected item
		final ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
		final int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		final int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		final int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
		
		// Set up the course-category cursor information
		final CursorCourseCategoryWeight courseCategoryCursor = (CursorCourseCategoryWeight) this.adapter.getCursor();
		courseCategoryCursor.moveToPosition(groupPos);
		
		// Trigger the right action
		switch (type) {
			case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
				// Trigger the right category action
				switch (item.getItemId()) {
					case R.id.menu_item_view_category_weight:
						this.showViewCategoryWeightDialog(courseCategoryCursor.getColCategoryName(),
								courseCategoryCursor.getColWeight());
						return true;
					case R.id.menu_item_edit_category_weight:
						this.showEditCategoryWeightDialog(courseCategoryCursor.getColId(),
								courseCategoryCursor.getColWeight());
						return true;
					case R.id.menu_item_rename_category:
						this.showRenameCategoryDialog(courseCategoryCursor.getColId(),
								courseCategoryCursor.getColCategoryName());
						return true;
					case R.id.menu_item_delete_category:
						this.showDeleteCategoryDialog(courseCategoryCursor.getColId(),
								courseCategoryCursor.getColCategoryName());
						return true;
					default:
						return super.onContextItemSelected(item);
				}
			case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
				// Set up the task cursor information
				final CursorTask taskCursor = (CursorTask) this.adapter.getChildrenCursor(courseCategoryCursor);
				taskCursor.moveToPosition(childPos);
				
				// Trigger the right category option
				switch (item.getItemId()) {
					case R.id.menu_item_view_task:
						this.startActivity(new Intent(this.getApplicationContext(),
								TaskActivity.class).putExtra(this.getString(R.string.intent_extra_taskId),
								taskCursor.getColId()));
						taskCursor.close();
						return true;
					case R.id.menu_item_edit_task:
						this.startActivity(new Intent(this.getApplicationContext(),
								EditTaskActivity.class).putExtra(this.getString(R.string.intent_extra_taskId),
								taskCursor.getColId())
								.putExtra(this.getString(R.string.intent_extra_courseId),
										taskCursor.getColCourseId()));
						taskCursor.close();
						return true;
					case R.id.menu_item_rename_task:
						this.showRenameTaskDialog(taskCursor.getColId(),
								taskCursor.getColName());
						taskCursor.close();
						return true;
					case R.id.menu_item_delete_task:
						this.showDeleteTaskDialog(taskCursor.getColId(),
								taskCursor.getColName());
						taskCursor.close();
						return true;
					default:
						taskCursor.close();
						return super.onContextItemSelected(item);
				}
			default: // ExpandableListView.PACKED_POSITION_TYPE_NULL
				Log.wtf("BackpackEDU",
						"Packed position is null.");
				return super.onContextItemSelected(item);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @param v
	 *            XXX
	 * @param menuInfo
	 *            XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	@Override
	public void onCreateContextMenu(final ContextMenu menu,
			final View v,
			final ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu,
				v,
				menuInfo);
		// Get information about the selected item
		final ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
		final int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		final int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		final int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
		
		// Get ready to show the context menu
		final MenuInflater inflater = this.getMenuInflater();
		final CursorCourseCategoryWeight courseCategoryCursor = (CursorCourseCategoryWeight) this.adapter.getCursor();
		courseCategoryCursor.moveToPosition(groupPos);
		switch (type) {
			case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
				// Show the category context menu
				menu.setHeaderTitle(courseCategoryCursor.getColCategoryName());
				inflater.inflate(R.menu.context_tasklist_category,
						menu);
				break;
			case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
				// Show the task context menu
				final CursorTask taskCursor = (CursorTask) this.adapter.getChildrenCursor(courseCategoryCursor);
				taskCursor.moveToPosition(childPos);
				menu.setHeaderTitle(taskCursor.getColName());
				taskCursor.close();
				inflater.inflate(R.menu.context_tasklist_task,
						menu);
				break;
			default: // ExpandableListView.PACKED_POSITION_TYPE_NULL
				Log.wtf("BackpackEDU",
						"Packed position is null.");
				break;
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		this.getMenuInflater()
				.inflate(R.menu.options_tasklist,
						menu);
		return true;
	}
	
	/**
	 * XXX
	 * 
	 * @param groupPosition
	 *            XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ExpandableListActivity#onGroupCollapse(int)
	 */
	@Override
	public void onGroupCollapse(final int groupPosition) {
		if (!this.openedGroups.remove(Integer.valueOf(groupPosition))) {
			Log.e("BackpackEDU",
					"Could not remove group position from opened group list.");
		}
		super.onGroupCollapse(groupPosition);
	}
	
	/**
	 * XXX
	 * 
	 * @param groupPosition
	 *            XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ExpandableListActivity#onGroupExpand(int)
	 */
	@Override
	public void onGroupExpand(final int groupPosition) {
		this.openedGroups.add(Integer.valueOf(groupPosition));
		super.onGroupExpand(groupPosition);
	}
	
	/**
	 * XXX
	 * 
	 * @param item
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_item_add_category:
				this.showAddCategoryDialog();
				return true;
			case R.id.menu_item_add_task:
				this.startActivity(new Intent(this.getApplicationContext(),
						EditTaskActivity.class).putExtra(this.getString(R.string.intent_extra_courseId),
						this.courseId));
				return true;
			case R.id.menu_item_settings:
				this.startActivity(new Intent(this.getApplicationContext(),
						SettingsActivity.class));
				return true;
			case R.id.menu_item_about:
				this.startActivity(new Intent(this.getApplicationContext(),
						AboutActivity.class));
				return true;
			case R.id.menu_item_help:
				this.startActivity(new Intent(this.getApplicationContext(),
						HelpActivity.class));
				return true;
			default:
				Log.wtf("BackpackEDU",
						"Undefined options menu item.");
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onPrepareOptionsMenu(final Menu menu) {
		final MenuItem item = menu.findItem(R.id.menu_item_add_task);
		if (item != null) {
			// Don't show 'Add task' if there are no categories
			if (this.adapter.getCursor()
					.getCount() == 0) {
				item.setEnabled(false);
			} else {
				item.setEnabled(true);
			}
		}
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * XXX
	 * 
	 * @param savedInstanceState
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ActivityGroup#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.activity_task_list);
		
		// Calling intent
		final Intent callingIntent = this.getIntent();
		this.courseId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_courseId),
				-1);
		
		// Start the database helper
		TaskListActivity.dbHelper = new BackpackEduDatabaseHelper(this);
		
		// Fill the data
		final ContentValues criteria = new ContentValues();
		criteria.put(CourseCategoryWeight.COURSE_ID,
				Long.valueOf(this.courseId));
		final CursorCourseCategoryWeight courseCategoryCursor = TaskListActivity.dbHelper.getCourseCategoryWeight(criteria,
				new String[] { CourseCategoryWeight.CATEGORY_NAME },
				true);
		this.startManagingCursor(courseCategoryCursor);
		
		// Set up the adapter
		this.adapter = new TaskListCursorTreeAdapter(this,
				courseCategoryCursor,
				R.layout.category,
				new String[] { CourseCategoryWeight.CATEGORY_NAME },
				new int[] { R.id.tv_category },
				R.layout.item,
				new String[] { Task.NAME },
				new int[] { R.id.tv_item });
		this.setListAdapter(this.adapter);
		
		// Expand the groups
		this.openedGroups = new ArrayList<Integer>();
		for (int i = 0; i < this.adapter.getGroupCount(); ++i) {
			this.getExpandableListView()
					.expandGroup(i);
		}
		
		// Let this view have a context menu
		this.registerForContextMenu(this.getExpandableListView());
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		TaskListActivity.dbHelper.close();
		super.onDestroy();
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	@SuppressWarnings("unchecked")
	protected void onRestart() {
		// Requery the category cursor
		// TODO [Chris W] Do I actually need this?
		this.adapter.notifyDataSetChanged();
		
		// Reopen all the groups that were open
		// TODO test this after deleting a category
		final Object clone = this.openedGroups.clone();
		if (!(clone instanceof ArrayList<?>)) {
			Log.e("BackpackEDU",
					"Cloned list is not an array list.");
			throw new ClassCastException("Cloned list is not an array list.");
		}
		
		final ArrayList<Integer> opened = (ArrayList<Integer>) clone;
		for (final Integer groupPos : opened) {
			this.getExpandableListView()
					.expandGroup(groupPos.intValue());
		}
		
		super.onRestart();
	}
	
	/**
	 * XXX
	 */
	private void showAddCategoryDialog() {
		final LayoutInflater inflater = this.getLayoutInflater();
		final View layout = inflater.inflate(R.layout.dialog_add_category,
				(ViewGroup) this.findViewById(R.id.dialog_add_category));
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout)
				.setTitle(R.string.menu_title_add_category)
				.setPositiveButton("Add",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								final EditText inputCategory = (EditText) layout.findViewById(R.id.add_category);
								final EditText inputWeight = (EditText) layout.findViewById(R.id.input_categoryWeight);
								final String newCategory = inputCategory.getText()
										.toString()
										.trim();
								final String weightString = inputWeight.getText()
										.toString()
										.trim();
								
								ContentValues criteria = new ContentValues();
								criteria.put(Course.ID,
										Long.valueOf(TaskListActivity.this.courseId));
								final CursorCourse courseCursor = TaskListActivity.dbHelper.getCourse(criteria,
										null,
										true);
								criteria = new ContentValues();
								if (!weightString.equals("")) {
									final Double catWeight = Double.valueOf(weightString);
									if (catWeight.doubleValue() > 100.0) {
										Toast.makeText(TaskListActivity.this,
												"Weight cannot excede 100%!",
												Toast.LENGTH_LONG)
												.show();
										return;
									}
									criteria.put(CourseCategoryWeight.WEIGHT,
											catWeight);
								}
								
								final boolean addOk = TaskListActivity.dbHelper.addCourseCategoryWeight(courseCursor.getColName(),
										courseCursor.getColSemesterName(),
										newCategory,
										criteria);
								if (addOk) {
									TaskListActivity.this.adapter.getCursor()
											.requery();
								} else {
									Toast.makeText(TaskListActivity.this,
											"Category \""
													+ newCategory
													+ "\" already exists!",
											Toast.LENGTH_LONG)
											.show();
								}
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param categoryId
	 *            XXX
	 * @param categoryName
	 *            XXX
	 */
	private void showDeleteCategoryDialog(final long categoryId,
			final String categoryName) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.menu_title_delete_category)
				.setMessage("Are you sure you want to delete the category \""
						+ categoryName
						+ "\" and all of its associated tasks?")
				.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								TaskListActivity.dbHelper.deleteCourseCategoryWeight(categoryId);
								TaskListActivity.this.adapter.getCursor()
										.requery();
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param taskId
	 *            XXX
	 * @param taskName
	 *            XXX
	 */
	private void showDeleteTaskDialog(final long taskId,
			final String taskName) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.menu_title_delete_task)
				.setMessage("Are you sure you want to delete the task \""
						+ taskName
						+ "\" ?")
				.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								TaskListActivity.dbHelper.deleteTask(taskId);
								TaskListActivity.this.adapter.notifyDataSetChanged();
								
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param categoryId
	 *            XXX
	 * @param categoryName
	 *            XXX
	 * @param weight
	 *            XXX
	 */
	private void showEditCategoryWeightDialog(final long categoryId,
			final Double weight) {
		final LayoutInflater inflater = this.getLayoutInflater();
		final View layout = inflater.inflate(R.layout.dialog_edit_category_weight,
				(ViewGroup) this.findViewById(R.id.dialog_edit_category_weight));
		final EditText inputWeight = (EditText) layout.findViewById(R.id.edit_category_weight);
		if (weight != null) {
			inputWeight.setText(weight.toString());
			inputWeight.selectAll();
		}
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout)
				.setTitle(R.string.menu_title_edit_category_weight)
				.setPositiveButton("Edit",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								final String weightString = inputWeight.getText()
										.toString()
										.trim();
								final ContentValues criteria = new ContentValues();
								if (!weightString.equals("")) {
									final Double catWeight = Double.valueOf(weightString);
									if (catWeight.doubleValue() > 100.0) {
										Toast.makeText(TaskListActivity.this,
												"Weight cannot excede 100%!",
												Toast.LENGTH_LONG)
												.show();
										return;
									}
									criteria.put(CourseCategoryWeight.WEIGHT,
											catWeight);
								}
								final boolean editOk = TaskListActivity.dbHelper.editCourseCategoryWeight(categoryId,
										criteria);
								if (editOk) {
									TaskListActivity.this.adapter.getCursor()
											.requery();
								} else {
									Log.wtf("BackpackEDU",
											"Edit weight failed!");
								}
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param categoryId
	 *            XXX
	 * @param categoryName
	 *            XXX
	 */
	private void showRenameCategoryDialog(final long categoryId,
			final String categoryName) {
		final LayoutInflater inflater = this.getLayoutInflater();
		final View layout = inflater.inflate(R.layout.dialog_rename_category,
				(ViewGroup) this.findViewById(R.id.dialog_rename_category));
		final EditText editText = (EditText) layout.findViewById(R.id.edit_category);
		editText.setText(categoryName);
		editText.selectAll();
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout)
				.setTitle(R.string.menu_title_rename_category)
				.setPositiveButton("Rename",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								final String newCategory = editText.getText()
										.toString()
										.trim();
								final ContentValues criteria = new ContentValues();
								criteria.put(CourseCategoryWeight.CATEGORY_NAME,
										newCategory);
								final boolean editOk = TaskListActivity.dbHelper.editCourseCategoryWeight(categoryId,
										criteria);
								if (editOk) {
									TaskListActivity.this.adapter.getCursor()
											.requery();
								} else {
									Toast.makeText(TaskListActivity.this,
											"Category \""
													+ newCategory
													+ "\" already exists!",
											Toast.LENGTH_LONG)
											.show();
								}
								
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param taskId
	 *            XXX
	 * @param taskName
	 *            XXX
	 */
	private void showRenameTaskDialog(final long taskId,
			final String taskName) {
		final LayoutInflater inflater = this.getLayoutInflater();
		final View layout = inflater.inflate(R.layout.dialog_rename_task,
				(ViewGroup) this.findViewById(R.id.dialog_rename_task));
		final EditText editText = (EditText) layout.findViewById(R.id.edit_task);
		editText.setText(taskName);
		editText.selectAll();
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout)
				.setTitle(R.string.menu_title_rename_task)
				.setPositiveButton("Rename",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								final String newTask = editText.getText()
										.toString()
										.trim();
								final ContentValues criteria = new ContentValues();
								criteria.put(Task.NAME,
										newTask);
								final boolean editOk = TaskListActivity.dbHelper.editTask(taskId,
										criteria);
								if (editOk) {
									TaskListActivity.this.adapter.notifyDataSetChanged();
								} else {
									Toast.makeText(TaskListActivity.this,
											"Task \""
													+ newTask
													+ "\" already exists!",
											Toast.LENGTH_LONG)
											.show();
								}
								
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * XXX
	 * 
	 * @param categoryName
	 *            XXX
	 * @param weight
	 *            XXX
	 */
	private void showViewCategoryWeightDialog(final String categoryName,
			final Double weight) {
		final LayoutInflater inflater = this.getLayoutInflater();
		final View layout = inflater.inflate(R.layout.dialog_view_category_weight,
				(ViewGroup) this.findViewById(R.id.dialog_view_category_weight));
		final TextView tvWeight = (TextView) layout.findViewById(R.id.view_category_weight);
		tvWeight.setText(weight.toString());
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout)
				.setTitle(categoryName)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								dialog.dismiss();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}
}
